package vendas.web.action;

import gminet.infra.business.BusinessException;
import gminet.infra.db.TransactionException;
import gminet.infra.web.WebException;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import vendas.business.AdministratorBusiness;
import vendas.dto.User;
import vendas.dto.UserType;

@ManagedBean(name = "administratorAction")
@RequestScoped
public class AdministratorAction extends WebAction {

    private static final long serialVersionUID = 8699535689521195806L;

    private User user;

    private List<User> users;

    public AdministratorAction() {
    }

    public String prepareEditUser(int userId) throws WebException {

        verifyLogin(UserType.ADMINISTRATOR);
        String pageReturn = "adminUserEdit";
        try {
            this.user = AdministratorBusiness.findByPK(userId);
            if (this.user == null) {
                throw new WebException("Usuário não encontrado.");
            }
        } catch (BusinessException be) {
            addBusinessException("adminUsersList", be);
            pageReturn = listUsers();
        } catch (TransactionException te) {
            throw new WebException(te);
        }
        return pageReturn;
    }

    public String editUser(User user) throws WebException {

        verifyLogin(UserType.ADMINISTRATOR);
        String pageReturn = "adminUsersList";
        try {
            AdministratorBusiness.updateUser(user);
            this.user = AdministratorBusiness.findByPK(user.getId());
            if (this.user == null) {
                throw new WebException("Usuário não encontrado.");
            }
        } catch (BusinessException be) {
            addBusinessException("adminUserEdit", be);
            pageReturn = "adminUserEdit";
        } catch (TransactionException te) {
            throw new WebException(te);
        }
        return pageReturn;
    }

    public String listUsers() throws WebException {

        verifyLogin(UserType.ADMINISTRATOR);
        String pageReturn = "adminUsersList";
        try {
            setUsers(AdministratorBusiness.listUsers());
        } catch (BusinessException be) {
            addBusinessException("adminUsersList", be);
        } catch (TransactionException te) {
            throw new WebException(te);
        }
        return pageReturn;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

}
